import createError from 'http-errors';
import express, { Request, Response, NextFunction } from 'express';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';

import indexRouter from './routes/index';

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 中间件配置
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 路由配置
app.use('/', indexRouter);

// 捕获 404 错误并转发到错误处理程序
app.use((req: Request, res: Response, next: NextFunction) => {
    next(createError(404));
});

// 错误处理程序
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
    // 设置本地变量，仅在开发环境中提供错误信息
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // 设置响应状态码
    res.status((err as { status?: number }).status || 500);

    // 渲染错误页面
    res.render('error');
});

export default app;